<script setup>
import { ref, onMounted } from 'vue';
import { getAccount, login } from '@/api';
import { useUserStore } from '@/stores';
import { useRouter } from 'vue-router';
const router = useRouter();
const userStore = useUserStore();
const username = ref('');
const password = ref('');

//系统提示
const sysWarn = () => {
  showDialog({
    title:"系统提醒",
    message: '系统暂不可用，请退出登录页重新进入或联系管理员！',
    theme: 'round-button',
  }).then(() => {
  }).catch(() => {
  });
}

const callGetAccount = () => {
  //获取账号
  getAccount().then(res => {
    username.value = res.data;
  }).catch(err => {
    sysWarn();
  });
}

//调用登录
const callLogin = () => {
  if(!username.value){
    sysWarn();
    return;
  }
  let datas = {
    username: username.value,
    password: password.value
  }
  //登录
  login(datas).then(res => {
    showNotify({ type: 'success', message: '登录成功', duration: 500 });
    userStore.setToken(res.token);
    router.push('/home');
  }).catch(err => {
    password.value = '';
    showNotify({ type: 'danger', message: err.msg, duration: 2000});
  });
}

//绑定提交登录按钮
const onSubmit = async() => {
  //调用登录
  callLogin();
}

//初始加载账号
onMounted(() => {
  callGetAccount();
})


</script>

<template>

  <van-form @submit="onSubmit" class="loginbox">
    <div class="titlebox">
      <img src="@/assets/logo.png" style="border-radius: 50%" width="100" height="100">
    </div>
    <van-cell-group inset>
      <van-field v-model="username" type="hidden" name="username" />
      <van-field ref="passwordRef" v-model="password" type="password" name="password" placeholder="请输入密码"
        :rules="[{ required: true, message: '密码不能为空' }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<style scoped>

.titlebox{
  text-align: center;
/*  margin-top: 27%;
  margin-bottom: 3%;
  font-weight: bold;*/
}

.loginbox{
  width: 80%;
  margin: 0 auto;
  margin-top: 30%;
  padding-top: 20px;
  border: 1px solid #EBEDF0;
  border-radius: 1rem;
  box-shadow: 0 0 2rem #EBEDF0;
}
.loginbox .van-field{
  position: static;
}


</style>